package com.aurora.demo.service;

import com.aurora.demo.repository.ImageRepository;
import com.aurora.demo.entity.Image;
import com.aurora.demo.util.ImageUtil;
import org.bson.types.Binary;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@Service
public class ImageService {

    @Autowired
    private ImageRepository imageRepository;

    @Autowired
    private RedisTemplate redisTemplate;

    public List<Image> findALl() {
        List<Image> images = imageRepository.findAll();

        return images;
    };

    public Image findByName(String name) {
        Image image;
        if(redisTemplate.opsForHash().hasKey("image", name)) {
            image = (Image) redisTemplate.opsForHash().get("image", name);
        } else {
            image = imageRepository.findByName(name);
            redisTemplate.opsForHash().put("image", name, image);
        }
        return image;
    }

    public void save(MultipartFile file) {
        Image image = new Image();
        String name = file.getOriginalFilename().substring(0, 13);
        image.setName(name.substring(0, 13));

        try {
            byte [] bytes = file.getBytes();
            image.setRawpic(new Binary(bytes));
            imageRepository.save(image);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
